package site.hanzhe.filters;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.core.annotation.Order;
import site.hanzhe.exception.AESException;
import site.hanzhe.exception.TypeConverterException;
import site.hanzhe.utils.BlogUtil;
import site.hanzhe.utils.Constant;
import site.hanzhe.utils.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter("/api/admin/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("token");
        try {
            String sessionId = req.getSession().getId();
            BlogUtil.validateToken(token, sessionId);
        } catch (NullPointerException e) {
            R r = R.error(Constant.RESULT_CODE_TOKEN_ERROR, "请先登录");
            this.refuse(resp, r);
            return;
        } catch (JWTDecodeException e) {
            R r = R.error(Constant.RESULT_CODE_TOKEN_ERROR, "Token无效，请重新登录");
            this.refuse(resp, r);
            return;
        } catch (SignatureVerificationException e) {
            R r = R.error(Constant.RESULT_CODE_TOKEN_ERROR, "Token解密失败，请重新登录");
            this.refuse(resp, r);
            return;
        } catch (TokenExpiredException e) {
            R r = R.error(Constant.RESULT_CODE_TOKEN_ERROR, "登录超时，请重新登录");
            this.refuse(resp, r);
            return;
        }
        chain.doFilter(req, resp);
    }

    public void refuse(HttpServletResponse resp, R r) {
        resp.setCharacterEncoding("UTF-8");
        try {
            String json = BlogUtil.mapToJson(r);
            resp.getWriter().write(json);
        } catch (IOException | TypeConverterException e) {
            e.printStackTrace();
        }
    }

}